package com.seeyon.apps.globalexception;

import com.seeyon.apps.wpscoordination.common.BusinessException;
import com.seeyon.apps.wpscoordination.common.JsonResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindException;
import org.springframework.validation.Errors;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import java.util.Map;
import java.util.Set;

@ControllerAdvice
@RestController
@Slf4j
public class GlobalException {

    @ExceptionHandler(Exception.class)
    public Map handle(Exception e){
        JsonResult jsonResult = new JsonResult();
        if(e instanceof BusinessException){
            BusinessException be=(BusinessException)e;
            jsonResult.setCode(be.getExceptionCode().getCode());
            jsonResult.setMsg(be.getExceptionCode().getMessage());
        }else if(e instanceof ConstraintViolationException){
            ConstraintViolationException ec=(ConstraintViolationException)e;
            StringBuilder errorInfo = new StringBuilder();
            String errorMessage ;
            Set<ConstraintViolation<?>> violations = ec.getConstraintViolations();
            for (ConstraintViolation<?> item : violations) {
                errorInfo.append(item.getMessage()).append(",");
            }
            errorMessage = errorInfo.toString().substring(0,
                    errorInfo.toString().length()-1);
            jsonResult.setCode("0");
            jsonResult.setMsg(errorMessage);
            return jsonResult.getMap();

        }else{
            jsonResult.setCode("500");
            jsonResult.setMsg("服务器开小差了");
            log.info("-------------------------------------------------------------------------------");
            log.info(e.getMessage());
            StackTraceElement[] stackTrace = e.getStackTrace();
            for (StackTraceElement stackTraceElement : stackTrace) {
                log.info(String.valueOf(stackTraceElement));
            }

        }
        return jsonResult.getMap();
    }

    // 处理第一种校验异常: 将异常信息拼接,返回给前端显示
    @ExceptionHandler({BindException.class,
            MethodArgumentNotValidException.class})
    public Map handleBindException(Errors errors){
        JsonResult jsonResult = new JsonResult();
        jsonResult.setCode("0");
        StringBuilder stringBuilder = new StringBuilder();
        errors.getAllErrors().forEach(error->{
            stringBuilder.append(error.getDefaultMessage()+",");
        });
        jsonResult.setMsg(stringBuilder.toString());
        return jsonResult.getMap();
    }

}